package com.simon.train.business.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simon.train.business.domain.TrainStation;
import com.simon.train.business.domain.TrainStationExample;
import com.simon.train.business.dto.TrainStationQueryDto;
import com.simon.train.business.dto.TrainStationSaveDto;
import com.simon.train.business.mapper.TrainStationMapper;
import com.simon.train.business.vo.TrainStationQueryVO;
import com.simon.train.common.exception.BusinessException;
import com.simon.train.common.exception.BusinessExceptionEnum;
import com.simon.train.common.util.SnowUtil;
import com.simon.train.common.vo.PageVO;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TrainStationService {

    private static final Logger LOG = LoggerFactory.getLogger(TrainStationService.class);

    @Resource
    private TrainStationMapper trainStationMapper;

    public void SaveTrainStation(TrainStationSaveDto trainStationSaveDto){
        TrainStation trainStation = BeanUtil.copyProperties(trainStationSaveDto, TrainStation.class);
        if (ObjectUtil.isNull(trainStation.getId())){
            //对于首次保存 也就是新增 需要对字段单独做处理
            TrainStation stationDB = SelectByUnique(trainStationSaveDto.getTrainCode(),
                    trainStationSaveDto.getIndex());

            if(ObjectUtil.isNotEmpty(stationDB)){
                throw new BusinessException(BusinessExceptionEnum.BUSINESS_TRAIN_STATION_INDEX_UNIQUE_ERROR);
            }

            stationDB = SelectByUnique(trainStationSaveDto.getTrainCode(),
                    trainStationSaveDto.getName());

            if(ObjectUtil.isNotEmpty(stationDB)){
                throw new BusinessException(BusinessExceptionEnum.BUSINESS_TRAIN_STATION_NAME_UNIQUE_ERROR);
            }

            trainStation.setId(SnowUtil.getSnowflakeNextId());
            DateTime time = DateTime.now();
            trainStation.setCreateTime(time);
            trainStation.setUpdateTime(time);
            trainStationMapper.insert(trainStation);
        } else {
            trainStation.setUpdateTime(DateTime.now());
            trainStationMapper.updateByPrimaryKey(trainStation);
        }

    }

    /**
     * 唯一键查询 针对traincode-index
     * @param trainCode
     * @param index
     * @return
     */
    private TrainStation SelectByUnique(String trainCode, Integer index) {
        TrainStationExample trainStationExample = new TrainStationExample();
        trainStationExample.createCriteria()
                .andTrainCodeEqualTo(trainCode)
                .andIndexEqualTo(index);
        List<TrainStation> list = trainStationMapper.selectByExample(trainStationExample);
        if(CollUtil.isNotEmpty(list)){
            return list.get(0);
        }else return null;
    }

    /**
     * 唯一键查询 针对traincode-name
     * @param trainCode
     * @param name
     * @return
     */
    private TrainStation SelectByUnique(String trainCode, String name) {
        TrainStationExample trainStationExample = new TrainStationExample();
        trainStationExample.createCriteria()
                .andTrainCodeEqualTo(trainCode)
                .andNameEqualTo(name);
        List<TrainStation> list = trainStationMapper.selectByExample(trainStationExample);
        if(CollUtil.isNotEmpty(list)){
            return list.get(0);
        }else return null;
    }

    public PageVO<TrainStationQueryVO> QueryTrainStationList(TrainStationQueryDto trainStationQueryDto){
        TrainStationExample trainStationExample = new TrainStationExample();
        trainStationExample.setOrderByClause("train_code asc, `index` asc");
        TrainStationExample.Criteria criteria = trainStationExample.createCriteria();

        if (ObjectUtil.isNotEmpty(trainStationQueryDto.getTrainCode())){
            criteria.andTrainCodeEqualTo(trainStationQueryDto.getTrainCode());
        }

        LOG.info("当前请求的页码：{}", trainStationQueryDto.getPage());
        LOG.info("每页条数：{}", trainStationQueryDto.getPageSize());

        PageHelper.startPage(trainStationQueryDto.getPage(),trainStationQueryDto.getPageSize());
        List<TrainStation> trainStationList = trainStationMapper.selectByExample(trainStationExample);

        PageInfo<TrainStation> pageInfo = new PageInfo<>(trainStationList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        List<TrainStationQueryVO> lists = BeanUtil.copyToList(trainStationList, TrainStationQueryVO.class);
        PageVO<TrainStationQueryVO> pageVO = new PageVO<>();
        pageVO.setList(lists);
        pageVO.setTotal(pageInfo.getTotal());

        return pageVO;
    }

    public void deleteTrainStation(Long id) {
        trainStationMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据trainCode直接查询出所有的车站信息
     * @param trainCode
     * @return
     */
    public List<TrainStation> SelectByTrainCode(String trainCode) {
        TrainStationExample trainStationExample = new TrainStationExample();
        trainStationExample.setOrderByClause("`index` asc");
        trainStationExample.createCriteria().andTrainCodeEqualTo(trainCode);
        /**
         * Mybatis默认查询结果为空时 会返回空 而不是空指针 从而不会出现空指针异常
         */
        return trainStationMapper.selectByExample(trainStationExample);
    }
}
